package com.dzsw.redis.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.integration.redis.util.RedisLockRegistry;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

public class DatacenterIdAndWorkerIdHelper implements Runnable {

    private RedisTemplate redisTemplate;

    private RedisLockRegistry redisLockRegistry;

    public DatacenterIdAndWorkerIdHelper(RedisTemplate redisTemplate,
                                         RedisLockRegistry redisLockRegistry) {
        this.redisTemplate = redisTemplate;
        this.redisLockRegistry = redisLockRegistry;
    }

    /**
     * 生成Id配置
     *
     * @return
     * @throws Exception
     */
    public int computeDataCenterAndWorkId() {
        int childPath = -1;
        for (int i = 0; i < 1024; i++) {
            String key = Const.DATACENTER_WORKER_KEY + ":" + i;
            Boolean ret = redisTemplate.opsForValue().setIfAbsent(key, i);
            redisTemplate.expire(key, 60, TimeUnit.SECONDS);
            if (ret) {
                childPath = i;
                break;
            }
        }
        return childPath;
    }

    @Override
    public void run() {
        Lock lock = redisLockRegistry.obtain("test");
        try {
            int dcaw = this.computeDataCenterAndWorkId();
            System.out.println(String.format("VALUE=[%s], DC=[%s], WK=[%s]", dcaw, dcaw >> 5, dcaw & 0x1F));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
